package saati.core.concordance;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Math.pow;
import static saati.utils.ArrayUtil.findOccurrence;
import static saati.utils.ArrayUtil.getColumn;

public class RelationConcordanceCalculator extends AbstractConcordanceCalculator {

    @Override
    protected Double calculate(Double s) {
        Double sum = getTSummary();
        return ((12 * s) / (m * m * (n * n * n - n) - m * sum));
    }

    private Double getTSummary() {
        Double sum = 0d;
        List<Map<Integer, Integer>> groupList = getListOfGroups();
        for (Map<Integer, Integer> group : groupList) {
            for (Integer count : group.values()) {
                sum += (pow(count, 3d) - count);
            }
        }
        return sum;
    }

    private List<Map<Integer, Integer>> getListOfGroups() {
        List<Map<Integer, Integer>> groupList = new ArrayList<Map<Integer, Integer>>();
        for (int i = 0; i < m; i++) {
            {
                Map<Integer, Integer> groups = new HashMap<Integer, Integer>();
                for (int j = 0; j < n; j++) {
                    int occurrence = findOccurrence(getColumn(rangeMatrix, i), rangeMatrix[j][i]);
                    if (occurrence > 1) {
                        groups.put(rangeMatrix[j][i], occurrence);
                    }
                }
                groupList.add(groups);
            }
        }
        return groupList;
    }
}
